<template>
  <el-dialog :visible.sync="dialogVisible" title="创建新订单" width="1300px" :close-on-click-modal="false" v-drag2anywhere>
    <el-form :model="formData" ref="formData" label-width="120px" :rules="rules" size="mini">
      <el-row :gutter="10">
        <el-col :span="6">
          <el-form-item label="下单时间:" prop="orderdate">
            <el-date-picker v-model="formData.orderdate" type="datetime" value-format="yyyy-MM-dd HH:mm:ss"
              style="width: 100%;"></el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="订单编号:" prop="ordercode">
            <el-input v-model="formData.ordercode" placeholder="订单编号"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="订单渠道:" prop="platformid">
            <el-select v-model="formData.platformid" placeholder="请选择订单类型" @change="handlePlatformChange">
              <el-option v-for="(item,index) in platforms" :key="index" :value="item.id"
                :label="item.label"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="渠道点位:" prop="platformrate">
            <el-input-number v-model="formData.platformrate" style="width: 120px;" :step="0.01" :min="0" :max="1" @change="handleUpdateRmb" >
            </el-input-number>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="10">
        <el-col :span="12">
          <el-form-item label="合作商名称:" prop="supname">
            <el-select v-model="formData.supname" style="width: 100%;" @change="handleSupChange">
              <el-option v-for="(item,index) in suppliers" :label="item.name" :key="item.index" :value="item.name">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="合作商点位(%):" prop="suprate">
            <el-input-number v-model="formData.suprate" style="width: 120px;" :min="0"  @change="handleUpdateRmb" :max="100">
              <span slot="suffix">%</span>
            </el-input-number>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <span style="color:darkgrey;">说明: {{formData.supratememo}}</span>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="6">
          <el-form-item label="客户地区:" prop="region_ids">
            <el-cascader ref="cityregion" expand-trigger="hover" :options="regionList" v-model="formData.region_ids"
              :props="{value:'region_id',label:'region_name'}" @change="handleRegionChange" placeholder="请选择地区">
            </el-cascader>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="收货人:" prop="buyerinfo">
            <el-select v-model="formData.buyerinfo.buyer" filterable placeholder="客户姓名" @change="handleClientChanged"
              allow-create style="width: 100%;" clearable>
              <el-option v-for="(item,index) in clients" :key="item.id" :label="item.username"
                :value="{value:item,label:item.username}" :title="item.keyword"
                style="height: 50px; width: 300px;border-bottom: 1px solid #f7f8f8;">
                <div style="clear: both; padding: 0px; position: absolute; ">{{item.username}}</div>
                <div style="position: absolute;right: 10px;color: #bfbfbf; ">{{item.mobile}}</div>
                <div style="clear: both; padding: 0px; color: #bfbfbf; font-size: 12px; position: absolute;top:20px">
                  {{ item.address }}
                </div>
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="联系电话:" prop="mobile">
            <el-input placeholder="联系电话" v-model="formData.mobile"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="实际客户:" prop="client">
            <el-autocomplete v-model="formData.client" placeholder="实际客户"  :fetch-suggestions="querySearchAsync"
              style="width: 100%;" ></el-autocomplete>
          </el-form-item>
        </el-col>

      </el-row>

      <el-row>
        <el-col :span="12">
          <el-form-item label="详细地址:" prop="address">
            <el-input v-model="formData.address" placeholder="收货详细地址"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="业务员:" prop="saleman">
            <el-select v-model="formData.saleman" placeholder="业务员姓名">
              <el-option v-for="(item,index) in salelist" :label="item.name" :value="item.name"
                :key="item.id"></el-option>
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="6">
          <el-form-item label="客户单位:" prop="clientname">
              <el-input v-model="formData.clientname" placeholder="客户单位名称" clearable></el-input>
          </el-form-item>
        </el-col>


      </el-row>
      <el-row>
        <el-col>
          <el-form-item label="清单明细">
            <div style="height: 300px; overflow-y: auto;">
            <el-table :data="tableData" border height="100%">
              <el-table-column type="index" label="序号" align="center"></el-table-column>
              <el-table-column prop="sn" label="商品编码" align="center" width="120px"></el-table-column>
              <el-table-column prop="title" label="商品名称" show-overflow-tooltip></el-table-column>
              <el-table-column prop="platform" label="渠道" align="center" width="130px"></el-table-column>
              <el-table-column prop="unit" label="单位" width="100px" align="center" show-overflow-tooltip>
                <template v-slot="scope">
                  <el-input v-model="scope.row.unit" style="width: 100%;">
                  </el-input>
                </template>
              </el-table-column>
              <el-table-column prop="count" label="数量" align="center" width="110px">
                <template v-slot="scope">
                  <el-input v-model="scope.row.count" style="width: 100%;" @change="handleUpdateRmb">
                  </el-input>
                </template>
              </el-table-column>
              <el-table-column prop="price" label="单价" width="120px" align="center">
                <template v-slot="scope">
                  <el-input v-model="scope.row.price" style="width: 100%;" @change="handleUpdateRmb"></el-input>
                </template>
              </el-table-column>
              <el-table-column label="总价" width="120px" align="center">
                <template v-slot="scope">{{format2Number(scope.row.total,2)}}</template>
              </el-table-column>
              <el-table-column prop="supprice" label="折扣单价" width="100px" align="center">
                <template v-slot="scope">{{format2Number(scope.row.supprice,2)}}</template>
              </el-table-column>
              <el-table-column prop="suptotal" label="折扣小计" width="100px" align="center">
                <template v-slot="scope">{{format2Number(scope.row.suptotal,2)}}</template>
              </el-table-column>
            </el-table>
            </div>
            <div style="text-align: right; padding-right: 10px; margin-top: 10px;">
              <span style="width:200px; margin-right: 30px;">订单总额: {{format2Number(amount,2)}}</span> <span
                style="width:200px; margin-right: 30px;">应收总额: {{format2Number(ptamount,2)}}</span>
              <span style="width:200px;">折后总额: {{format2Number(supamount,2)}}</span>
            </div>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col>
          <el-form-item label="订单备注:">
            <el-input type="textarea" rows="3" v-model="formData.ordermemo" placeholder="备注信息"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>

      </el-row>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="dialogVisible = false" size="medium">取 消</el-button>
      <el-button type="primary" size="medium" @click="handleSave">保 存</el-button>
    </div>
  </el-dialog>
</template>

<script>
  export default {
    data() {
      var validatejdrate = (rule, value, callback) => {
        if (value == 0) {
          callback(); ///new Error("折扣率不能为0")
        } else {
          callback();
        }
      };
      return {
        dispatched: true,
        formData: {
          orderdate: '',
          ordercode: '',
          mordercode: '',
          type: '1',
          buyerinfo: {},
          saleman: '',
          buyer: "",
          mobile: '',
          region_ids: [],
          region_values: [],
          address: '',
          client: '',
          clientname:'',
          ordermemo: '',
          suprate: 0,
          supmemo: '',
          supid: -1,
          supname: '',
          platformid: -1,
          platform: '',
          platformrate: 0,
          platformratememo: '',
        },
        amount: 0,
        supamount: 0,
        ptamount: 0,
        platformid: -1,
        platform: '',
        platforms: [],
        rules: {
          ordercode: [{
            required: true,
            message: "请正确填写订单编号!",
            trigger: 'blur'
          }],
          orderdate: [{
            required: true,
            message: "请填正确填写下单时间!",
            trigger: 'blur'
          }],
          type: [{
            required: true,
            message: "请填正确填写下单类型!",
            trigger: 'blur'
          }],
          saleman:[{
            required: true,
               message: "请填写实际客户!",
              trigger: 'blur'
          }],
          buyerinfo: [{
            required: true,
            type: 'object',
            message: "请填正确填写收货人!",
            trigger: 'blur'
          }],
          mobile: [{
            required: true,
            message: "请填正确填写联系电话!",
            trigger: 'blur'
          }],
          region_ids: [{
            type: 'array',
            required: true,
            message: "请选择区域",
            trigger: 'change'
          }],
          address: [{
            required: true,
            message: "请填正确填写详细收货地址!",
            trigger: 'blur'
          }],
          supname: [{
            required: true,
            message: "请填为订单指定供应商!",
            trigger: 'blur'
          }],
          client: [{
            required: true,
            message: "客户名称!",
            trigger: 'blur'
          }],
          suprate: [{
              required: true,
              message: "请填写合适折扣率!",
              trigger: 'blur'
            },
            {
              validator: validatejdrate,
              trigger: 'blur'
            }
          ],
        },
        salelist: [],
        suppliers: [],
        regionList: [],
        tableData: [],
        dialogVisible: true,
        clients: []
      }
    },
    mounted() {
      this.loadRegions();
      this.loadSalemans();
    },
    methods: {
      init(platforms, suppliers, selection) {
        this.platforms = platforms;
        this.suppliers = suppliers;
        if (this.$refs.formData) {
          this.$refs.formData.resetFields();
        }
        this.tableData = [];

        var goods=[];
        selection.forEach(item=>{
            var g={
              id:item.id,
              sn:item.sn,
              title:item.title,
              model:item.model,
              brand:item.brand,
              unit:item.unit,
              price:item.price,
              platformid:item.platformid,
              platform:item.platform,
              count:1
            }
            goods.push(g);
        })


        this.tableData=goods;


        //this.tableData = JSON.parse(JSON.stringify(selection));

        //获取商品平台id
        if (this.tableData.length > 0) {
          this.platform = this.tableData[0].platform;
          this.formData.platformid = this.tableData[0].platformid;
          this.formData.platform = this.tableData[0].platform;

          this.platforms.forEach((item) => {
            if (item.id == this.formData.platformid) {
              this.formData.platformrate = parseFloat(item.rate);
            }
          })
        } else {
          this.platform = "";
        }
        console.log(this.formData);
        //获取选择平台的税率
        this.handleUpdateRmb();
        this.loadClient();
      },

      querySearchAsync(str, cb) {
        this.axios.post("api/admin/clientuser/filter", {
          username: str
        }).then(res => {
          if (res.data.code) {
            cb(res.data.data);
          }
        })
      },
      loadSalemans() {
        this.axios.post("api/admin/mate/list_op").then(res => {
          if (res.status == 200 && res.data.code == 0) {
            this.salelist = res.data.list;
          }
        })
      },

      loadClient() {
        this.axios.post("api/admin/clientuser/list").then(res => {
          if (res.status == 200 && res.data.code == 0) {
            this.clients = res.data.list;
          }
        })
      },
      handleClientChanged(item) {
        console.log(item);
        if (item == "") {
          this.formData.username = this.formData.address = this.formData.mobile = "";
          this.formData.region_ids = [];
          this.formData.region_values = [];
        } else {
          if (typeof(item) != "string") {
            this.formData.username = item.value.username;
            this.formData.region_ids = item.value.region_ids;
            this.formData.region_values = item.value.region_values;
            this.formData.address = item.value.address;
            this.formData.mobile = item.value.mobile;
            this.formData.client=item.value.username;
            this.formData.clientname=item.value.company;
          } else {
            this.formData.username = item;
          }
        }
      },
      handleRegionChange: function(reg) {
        this.formData.region_ids = reg;
        this.formData.region_values = this.$refs["cityregion"].getCheckedNodes()[0].pathLabels;
      },
      loadRegions: function() {
        this.axios.post("api/common/region/list").then(res => {
          if (res.status == 200 && res.data.code == 0) {
            this.regionList = res.data.data;
          }
        })
      },
      loadSuppliers: function() {
        this.axios.post("api/admin/supplier/list").then((res) => {
          if (res.status == 200 && res.data.code == 0) {
            this.suppliers = res.data.list;
          }
        });
      },

      handleSupChange: function(sup) {
        var option = this.suppliers.filter(function(cur, index, a) {
          if (cur.name == sup) {
            return cur;
          }
        })[0];
        this.formData.supid = option.id;
        this.formData.supname = option.name;

        this.loadSupRate();

      },

      loadSupRate() {
        //根据渠道获取客户对应的点位
        this.axios.post("/api/admin/supplier/getrate", {
          supid: this.formData.supid,
          platform: this.formData.platform
        }).then((res) => {
          if (res.status == 200 && res.data.code == 1) {
            this.formData.suprate = res.data.rate;
            this.formData.supratememo = res.data.ratememo;
          } else {
            this.$message.error("获取供应商点位失败，采用默认点位");
            this.formData.suprate = res.data.rate;
            this.formData.supratememo = res.data.ratememo;
          }
          this.handleUpdateRmb();
        })
      },

      handlePlatformChange(platformid) {
        console.log(platformid);
        var option = this.platforms.filter(function(cur, index, a) {
          if (cur.id == platformid) {
            return cur;
          }
        })[0];
        this.formData.platformid = option.id;
        this.formData.platform = option.label;
        this.formData.platformrate = option.rate;
        this.formData.platformratememo = option.ratememo;

        for(var i=0;i<this.tableData.length;i++){
          this.tableData[i].platform=this.formData.platform;
          this.tableData[i].platformid=this.formData.platformid;
        }

        this.loadSupRate();
        this.handleUpdateRmb();
      },

      format2Number(value, len) {
        var f = parseFloat(value);
        var f = Math.round(value * 100) / 100;
        var s = f.toString();
        var rs = s.indexOf('.');
        if (rs < 0) {
          rs = s.length;
          s += '.';
        }
        while (s.length <= rs + len) {
          s += '0';
        }
        return s;
        return realVal;
      },
      handleUpdateRmb: function() {
        this.amount = 0;
        this.supamount = 0;
        this.ptamount = 0;
        this.tableData.map((item) => {
          item.price = item.price;
          item.total = item.price * item.count;
          item.ptprice = item.price * (100 - this.formData.platformrate) / 100;
          item.pttotal = item.ptprice * item.count;
          item.supprice = item.price * (100 - this.formData.suprate) / 100;
          item.suptotal = item.supprice * item.count;
          this.amount += item.total;
          this.supamount += item.suptotal;
          this.ptamount += item.pttotal;
        })

        this.tableData = JSON.parse(JSON.stringify(this.tableData));
      },
      handleGetPlatformRate() {

      },
      handleSave: function() {
        this.$refs.formData.validate(ok => {
          if (ok) {
            let params = {
              orderdate: this.formData.orderdate,
              ordercode: this.formData.ordercode,
              platformid: this.tableData[0].platformid,
              platform: this.tableData[0].platform,
              platformrate: this.formData.platformrate,

              region_ids: this.formData.region_ids,
              region_values: this.formData.region_values,

              supid: this.formData.supid,
              supname: this.formData.supname,
              suprate: this.formData.suprate,
              supratememo: this.formData.supratememo,

              buyer: this.formData.username,
              mobile: this.formData.mobile,
              address: this.formData.address,

              ordermemo: this.formData.ordermemo,
              client: this.formData.client,
              clientname:this.formData.clientname,

              goods: this.tableData,
              saleman: this.formData.saleman
            }
            this.axios.post("api/admin/product/parseorder", params).then(res => {
              if (res.status == 200 && res.data.code == 1) {
                this.$message({
                  message: "创建订单成功!",
                  showClose: true,
                  type: 'success',
                  duration: 1000
                });
                this.dialogVisible = false;
              } else {
                this.$message({
                  message: "创建订单失败!" + res.data.msg,
                  showClose: true,
                  type: 'error',
                  duration: 1000
                });
              }
            })
          }
        })
      }
    }
  }
</script>

<style>
</style>
